
// 关闭视频详情模态框
function closeVideoDetail() {
    let video = $("#ylVideo")
    video[0].pause();
    video[0].currentTime = 0;
    $("#videoDetailModal").removeClass("active");
}

// 点击模态框外部关闭
document.querySelector('.modal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeVideoDetail();
    }
});

// 导航项点击事件
const navItems = document.querySelectorAll('.nav-item');
navItems.forEach(item => {
    item.addEventListener('click', function(e) {
        //e.preventDefault();
        navItems.forEach(nav => nav.classList.remove('active'));
        this.classList.add('active');
        
        // 更新页面标题
        const title = this.querySelector('span').textContent;
        document.querySelector('.section-title').innerHTML = 
            `<i class="${this.querySelector('i').className}"></i> ${title}`;
    });
});


    
// 全选功能
$("#selectAll").click(function(){
	$(".review-list input").prop("checked",this.checked)
})


//----------------↑页面----------------↓ajax----------------
$(".review-list").on("click",".action-btn",function(){
	if($(this).text().toLowerCase().includes("预览".toLowerCase())){
		$("#videoDetailModal").addClass('active');
		$("#videoDetailModal>input").val($(this).parents(".review-item").find("input[type='hidden']").val())
		$(".info-value").eq(0).text($(this).parents(".review-item").find(".review-title").text())
		$(".info-value").eq(1).text($(this).parents(".review-item").find(".review-meta span").eq(0).text().split("：")[1])
		$(".info-value").eq(2).text($(this).parents(".review-item").find(".review-meta span").eq(3).text().split("：")[1])
		$(".info-value").eq(3).text($(this).parents(".review-item").find(".review-meta span").eq(1).text().split("：")[1])
		$(".info-value").eq(4).text($(this).parents(".review-item").find(".review-meta span").eq(2).text().split("：")[1])
		$(".info-value").eq(5).text("MP4")
		$(".info-value").eq(6).text($(this).parents(".review-item").find("#description").text())
		$(".modal-body video").prop("poster",$("#coverUrl").text())
		$(".modal-body source").prop("src",$(this).parents(".review-item").find("#videoUrl").text())
		$(".modal-body video")[0].load(); // 触发重新加载
	}
})



let currentPage = 1


$(".review-list").on("click",".action-btn",function(){
	let videoId = $(this).parents(".review-item").find("input[type='hidden']").val()
	if($(this).text().toLowerCase().includes("通过".toLowerCase())){
		if($(".review-item").length < 2){
			currentPage = 1
		}
		updateSomeVideoState(videoId,"通过",currentPage)
	}else if($(this).text().toLowerCase().includes("拒绝".toLowerCase())){
		if($(".review-item").length < 2){
			currentPage = 1
		}
		updateSomeVideoState(videoId,"拒绝",currentPage)
	}
})


$("#videoDetailModal").find(".action-btn").click(function(){
	let videoId = $("#videoDetailModal>input").val()
	if($(this).text().toLowerCase().includes("通过".toLowerCase())){
		updateSomeVideoState(videoId,"通过")
	}else if($(this).text().toLowerCase().includes("拒绝".toLowerCase())){
		updateSomeVideoState(videoId,"拒绝")
	}
})

$(".filter-select").on("change",function(){
	currentPage = 1
	queryAllNotVideo()
})
$(".date-input").on("change",function(){
	currentPage = 1
	queryAllNotVideo()
})
$(".success").click(function(){
	let successList = []
	$(".review-list input[type='checkbox']").each(function(){
		if($(this).prop("checked")){
			successList.push($(this).prev().val())
		}
	})
	if(successList.length > 0){
		if(currentPage > 1){
			currentPage--
		}
		updateSomeVideoState(successList,"通过")
	}
})
$(".delete").click(function() {
	let successList = []
	$(".review-list input[type='checkbox']").each(function(){
		if($(this).prop("checked")){
			successList.push($(this).prev().val())
		}
	})
	if(successList.length > 0){
		if(currentPage > 1){
			currentPage--
		}
		updateSomeVideoState(successList,"拒绝")
	}
})
queryAllNotVideo()
function queryAllNotVideo(pageNum = 1){
	let state = $(".filter-select").val()
	let startTime = $(".date-input").eq(0).val()
	let endTime = $(".date-input").eq(1).val()
	let timeDiff = (new Date(endTime) - new Date(startTime))/ (1000 * 60 * 60 * 24);
    if(timeDiff < 0){
    	promptAnimation("结束日期不得早于开始日期")
    	return;
    }
    let allViedoBox = $(".review-list")
	$.ajax({
		url:"queryAllNotVideoR",
		type:"post",
		data:{
			state:state,
			startTime:startTime,
			endTime:endTime,
			pageNum:pageNum
		},
		success:function(data){
			allViedoBox.empty()
			if(data.code == 200){
				let videos = data.data.data
				for(let i = 0;i<videos.length;i++){
					let video = videos[i]
					let totalTime = countVideoTime(video.duration)
					let state = video.status == 0?"待审核":video.status == 1?"已通过":"已拒绝"
					let addClass = "status-pending"
					if(video.status == 1){
						addClass = "status-reviewed"
					}else if(video.status == 2){
						addClass = "status-rejected"
					}
					let div = `
						<div class="review-item">
                            <div class="review-checkbox">
                            	<input type="hidden" value="${video.videoId}">
                                <input type="checkbox">
                            </div>
                            <div class="review-thumb">
                                <div class="play-btn" style="background: url(${video.coverUrl}) no-repeat;background-size:cover;"><i class="fas fa-play"></i></div>
                                <div class="video-duration">${totalTime}</div>
                                <div style="display:none;" id="coverUrl">${video.coverUrl}</div>
                                <div style="display:none;" id="videoUrl">${video.videoUrl}</div>
                            </div>
                            <div class="review-info">
                                <div class="review-title">${video.title}</div>
                                <div class="review-meta">
                                    <span><i class="fas fa-user"></i> 上传者：${video.username}</span>
                                    <span><i class="fas fa-clock"></i> 时长：${totalTime}</span>
                                    <span><i class="fas fa-database"></i> 大小：${video.videoSize}</span>
                                    <span><i class="fas fa-calendar"></i> 上传时间：${video.createTime}</span>
                                    <span style="display:none;" id="description">${video.description}</span>
                                </div>
                                <div class="review-status ${addClass}">${state}</div>
                            </div>
                            <div class="review-actions">
                                <button class="action-btn"">
                                    <i class="fas fa-eye"></i> 预览
                                </button>
                                <button class="action-btn success">
                                    <i class="fas fa-check"></i> 通过
                                </button>
                                <button class="action-btn delete">
                                    <i class="fas fa-times"></i> 拒绝
                                </button>
                            </div>
                        </div>
					`
					allViedoBox.append(div)
				}
				$(".pagination").css("display","flex")
				makePageBar(data.data)
			}else{
				let div = `
					<div style="width: 148px;margin: 17% auto;">
	                	<img src="img/ZFZJ.svg">
	                	<p style="text-align: center">没有找到哦~</p>
	                </div>
				`
				allViedoBox.append(div)
				$(".batch-select input").prop("checked",false)
				$(".pagination").css("display","none")
			}
		}
	
	})
}

function updateSomeVideoState(videoIds,text,page){
	let state = text == "通过"?1:2
	$.ajax({
		url:"updateSomeVideoState",
		type:"post",
		traditional: true,
		data:{
			videoIds:videoIds,
			state:state
		},
		success:function(data){
			if(data.code == 200){
				promptAnimation("视频"+text+"成功")
				if(text == "通过"){
					$(".batch-actions .success").html('<i class="fas fa-check"></i>已通过');
				}else{
					$(".batch-actions .success").html('<i class="fas fa-check"></i>批量通过');
				}
				queryAllNotVideo(page)
			}else{
				promptAnimation("视频"+text+"成功")
			}
		}
	})
}

function makePageBar(page) {
	$(".batch-select input").prop("checked",false)
    let pageBar = $(".pagination-controls");
    let navigatorNums = page.totalPageNum;
    pageBar.empty();

    let t = $(".pagination-info")
    t.empty()
    let start = (page.pageNum - 1) * page.pageSize + 1;
    let end = page.pageNum * page.pageSize;
    end = end > page.totalRows ? page.totalRows : end;
    let bottomPage = $("<div class='pagination-info'>显示"+`${start}`+"-"+`${end}`+" 条，共 "+`${page.totalRows}`+"条</div>");
    t.append(bottomPage)
    
    let prevPage = $("<button class='pagination-btn'><i class='fas fa-chevron-left'></i></button>").click(function() {
    	queryAllNotVideo(currentPage - 1);
        currentPage--
    });
    pageBar.append(prevPage);

    for (let i = 0; i < navigatorNums.length; i++) {
        let num = navigatorNums[i];
        let pageLink = $("<button class='pagination-btn'>"+num+"</button>").click(function() {
        	queryAllNotVideo(num);
            currentPage = num 
        });
        if (num == currentPage) {
            pageLink.addClass("active");
        }
        pageBar.append(pageLink);
    }

    let nextPage = $("<button class='pagination-btn'><i class='fas fa-chevron-right'></i></button>").click(function() {
    	queryAllNotVideo(currentPage + 1);
        currentPage++
    });
    pageBar.append(nextPage);
    

    if (!page.hasPrev) {
    	prevPage.prop("disabled",true)
    }
    if (!page.hasNext) {
    	nextPage.prop("disabled",true)
    }
}

function countVideoTime(totalSecond){
	let hous = parseInt(totalSecond/60/60)
	let minute = parseInt((totalSecond - hous*60*60)/60)
	let second = totalSecond - hous*60*60 - minute*60
	if(hous < 10){
		hous = "0"+hous
	}
	if(minute < 10){
		minute = "0"+minute
	}
	if(second < 10){
		second = "0"+second
	}
	let totalTime;
	if(hous == 0){
		totalTime = minute+":"+second
	}else{
		totalTime = hous+":"+minute+":"+second
	}
	return totalTime;
}


function promptAnimation(text) {
    let $prompt = $("#prompt");
    $prompt.text(text);
    
    // 新增：立即停止所有正在进行的动画并重置位置
    $prompt.stop(true, true).css("top", "-60px");

    // 清除之前的定时器（防止动画堆积）
    if ($prompt.data('timeoutId')) {
        clearTimeout($prompt.data('timeoutId'));
    }

    // 上升动画
    $prompt.animate({ top: 0 }, {
        duration: 240,
        easing: "linear",
        complete: function() {
            // 保存新的定时器ID到元素数据
            const timeoutId = setTimeout(function() {
                // 下降动画（同样添加中断机制）
                $prompt.stop(true, true).animate({ top: -60 }, {
                    duration: 240,
                    easing: "linear",
                    complete: function() {
                        // 动画完成后清除定时器ID
                        $prompt.removeData('timeoutId');
                        if($("#videoDetailModal").hasClass("active")){
                        	closeVideoDetail()
                        }
                    }
                });
            }, 1500);
            
            // 存储定时器ID用于后续清除
            $prompt.data('timeoutId', timeoutId);
        }
    });
}